<!-- 退料检验单管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验单编号" prop="rqcCode">
        <el-input
          v-model="queryParams.rqcCode"
          placeholder="请输入检验单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验单名称" prop="rqcName">
        <el-input
          v-model="queryParams.rqcName"
          placeholder="请输入检验单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验类型" prop="rqcType">
        <el-select v-model="queryParams.rqcType" placeholder="请选择检验类型" clearable size="small">
          <el-option
            v-for="dict in rqcTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检测结果" prop="checkResult">
        <el-select v-model="queryParams.checkResult" placeholder="请选择检测结果" clearable size="small">
          <el-option
            v-for="dict in checkResultOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择单据状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['qc:rqc:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qc:rqc:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qc:rqc:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="rqcList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
      style="width: 100%"
      :row-style="getRowStyle"
      :cell-style="{padding: '0px'}"
      :header-cell-style="{height: '40px', padding: '0px'}"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="检验单ID" align="center" prop="rqcId" v-if="false" />
      <el-table-column label="检验单编号" align="center" prop="rqcCode" min-width="120" fixed="left">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleView(scope.row)">{{ scope.row.rqcCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="检验单名称" align="center" prop="rqcName" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="检验类型" align="center" prop="rqcType" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="rqcTypeTag(scope.row.rqcType)">
            {{ formatRqcType(scope.row.rqcType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源单据类型" align="center" prop="sourceDocType" min-width="100">
        <template slot-scope="scope">
          <el-tag type="success">
            {{ formatSourceDocType(scope.row.sourceDocType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源单据编号" align="center" prop="sourceDocCode" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="物料编码" align="center" prop="materialCode" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="物料名称" align="center" prop="materialName" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="检测结果" align="center" prop="checkResult" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="checkResultTag(scope.row.checkResult)">
            {{ formatCheckResult(scope.row.checkResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTag(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['qc:rqc:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qc:rqc:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qc:rqc:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleDefectRecord(scope.row)"
            v-hasPermi="['qc:rqc:query']"
          >缺陷记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退料检验单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @closed="handleDialogClosed">
      <rqc-form
        ref="rqcForm"
        :form-data="form"
        :type="operationType"
        :key="'rqc-form-' + operationType + '-' + (form.rqcId || 'new')"
        @submit="submitForm"
        @cancel="cancel"
      />
    </el-dialog>

    <!-- 缺陷记录对话框 -->
    <defect-record-dialog
      :visible.sync="defectDialogVisible"
      title="退料检验单缺陷记录"
      :qcId="currentDefectRqcId"
      :qcType="4"
    />
  </div>
</template>

<script>
import { listQcRqc as listRqc, getQcRqc as getRqc, delQcRqc as delRqc, addQcRqc as addRqc, updateQcRqc as updateRqc } from "@/api/qc/ReturnInspection";
import RqcForm from "./components/RqcForm";
import DefectRecordDialog from "../components/DefectRecordDialog";
import { QcWebSocketBus } from "@/utils/qc-websocket"; // 导入质检WebSocket事件总线

export default {
  name: "ReturnInspection",
  components: {
    RqcForm,
    DefectRecordDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退料检验单表格数据
      rqcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 操作类型（add=添加，edit=修改，view=查看）
      operationType: "add",
      // 缺陷记录对话框显示状态
      defectDialogVisible: false,
      // 当前操作的缺陷记录相关的退料检验单ID
      currentDefectRqcId: null,
      // 检验类型选项
      rqcTypeOptions: [
        { value: "1", label: "来料检验" },
        { value: "2", label: "出货检验" },
        { value: "3", label: "过程检验" },
        { value: "4", label: "退料检验" }
      ],
      // 来源单据类型选项
      sourceDocTypeOptions: [
        { value: "1", label: "退料单" }
      ],
      // 检测结果选项
      checkResultOptions: [
        { value: "1", label: "合格" },
        { value: "2", label: "不合格" },
        { value: "3", label: "待检" }
      ],
      // 单据状态选项
      statusOptions: [
        { value: "1", label: "草稿" },
        { value: "2", label: "已提交" },
        { value: "3", label: "已审核" }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rqcCode: null,
        rqcName: null,
        rqcType: null,
        checkResult: null,
        status: null
      },
      // 表单参数
      form: {},

      // 待检高亮ID
      highlightId: null,
      
      // 已处理的消息ID集合，用于去重
      processedMessageIds: new Set(),
      
      // 消息过期时间（毫秒）
      messageExpirationTime: 5000
    };
  },
  created() {
    // 检查路由参数，获取检验单编号
    if (this.$route.query.inspectionCode) {
      // 使用检验单编号作为唯一查询条件
      this.queryParams.rqcCode = this.$route.query.inspectionCode;

      // 清空其他可能干扰查询的条件，确保查询精度
      Object.keys(this.queryParams).forEach(key => {
        if (key !== 'rqcCode' && key !== 'pageNum' && key !== 'pageSize') {
          this.queryParams[key] = null;
        }
      });

      this.$message.info('正在查找待检测单据，请稍候...');
    }
    this.getList();
    
    // 注册WebSocket事件处理程序
    this.registerWebSocketEvents();
    
    // 启动时清空消息ID集合
    this.processedMessageIds.clear();
  },
  
  beforeDestroy() {
    // 移除WebSocket事件监听
    this.unregisterWebSocketEvents();
  },
  methods: {
    // 注册WebSocket事件
    registerWebSocketEvents() {
      // 监听质检单创建事件
      QcWebSocketBus.$on('quality_check_created', this.handleQcInspectionCreated);
      
      // 监听质检单更新事件
      QcWebSocketBus.$on('quality_check_updated', this.handleQcInspectionUpdated);
    },
    
    // 移除WebSocket事件监听
    unregisterWebSocketEvents() {
      // 移除质检WebSocket事件监听
      QcWebSocketBus.$off('quality_check_created', this.handleQcInspectionCreated);
      QcWebSocketBus.$off('quality_check_updated', this.handleQcInspectionUpdated);
      
      // 清空消息ID集合
      this.processedMessageIds.clear();
    },
    
    // 处理质检单创建通知
    handleQcInspectionCreated(data) {
      console.log('收到质检单创建通知:', data);
      
      // 安全检查
      if (!data || !data.data) {
        console.warn('收到的质检单通知数据不完整:', data);
        return;
      }
      
      // 只处理退料检验类型的通知
      if (data.data.inspectionType === '4') {
        const messageId = data.data.messageId || `msg-${Date.now()}`;
        if (this.processedMessageIds.has(messageId)) {
          console.log('消息已处理，跳过:', messageId);
          return;
        }
        this.processedMessageIds.add(messageId);
        setTimeout(() => this.processedMessageIds.delete(messageId), this.messageExpirationTime);

        this.$notify({
          title: '新退料检验单通知',
          message: data.message || '新的退料检验单已创建，请及时处理',
          type: 'success',
          duration: 5000
        });

        if (data.data.inspectionId) {
          this.highlightId = data.data.inspectionId;
        }
        
        this.getList();
      }
    },
    
    // 处理质检单更新通知
    handleQcInspectionUpdated(data) {
      console.log('收到质检单更新通知:', data);
      
      // 安全检查
      if (!data || !data.data) {
        console.warn('收到的质检单更新通知数据不完整:', data);
        return;
      }
      
      // 只处理退料检验类型的通知
      if (data.data.inspectionType === '4') {
        this.$message.info(`退料检验单 ${data.data.inspectionCode} 已更新`);
        this.highlightId = null; // 更新时清除高亮
        this.getList();
      }
    },
    
    /** 查询退料检验单列表 */
    getList() {
      this.loading = true;
      listRqc(this.queryParams).then(response => {
        // 确保返回的数据是数组
        this.rqcList = Array.isArray(response.rows) ? response.rows : [];
        this.total = response.total || 0;

        // 如果使用了检验单编号查询，尝试找到对应记录并高亮显示
        if (this.$route.query.inspectionCode) {
          // 安全检查 - 确保rqcList是数组且不为空
          if (this.rqcList && this.rqcList.length > 0) {
            const foundItem = this.rqcList.find(item => item && item.rqcCode === this.$route.query.inspectionCode);
            if (foundItem && foundItem.rqcId) {
              // 记录ID用于高亮显示
              this.highlightId = foundItem.rqcId;

              this.$message.success('找到待检测单据，已高亮显示');
              // 滚动到对应行（通过DOM操作，延迟确保表格已渲染）
              this.$nextTick(() => {
                try {
                  const rows = document.querySelectorAll('.el-table__row');
                  if (rows && rows.length > 0) {
                    // 安全遍历行
                    rows.forEach((row, index) => {
                      if (index < this.rqcList.length &&
                          this.rqcList[index] &&
                          this.rqcList[index].rqcId == this.highlightId) {
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                      }
                    });
                  }
                } catch (error) {
                  console.error('滚动到高亮行时出错:', error);
                }
              });
            } else {
              // 未找到时，给出明确的提示，并提供查询建议
              this.$message.warning({
                message: '未找到指定编号的检验单，请尝试调整查询条件',
                duration: 5000
              });

              // 自动重置查询，重新获取完整列表，便于用户手动查找
              this.$confirm('是否重置查询条件，显示所有检验单?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetQuery();
              }).catch(() => {});
            }
          } else {
            this.$message.warning({
              message: '查询结果为空，未找到任何检验单',
              duration: 5000
            });
          }
        }
      }).catch(error => {
        console.error("获取列表失败:", error);
        this.$modal.msgError("数据加载失败");
        this.rqcList = []; // 确保发生错误时列表被重置为空数组
      }).finally(() => {
        this.loading = false;
      });
    },
    // 检验类型格式化
    formatRqcType(rqcType) {
      const option = this.rqcTypeOptions.find(item => item.value === rqcType);
      return option ? option.label : rqcType;
    },
    // 检验类型标签类型
    rqcTypeTag(rqcType) {
      switch (rqcType) {
        case '1': return 'primary';
        case '2': return 'success';
        case '3': return 'info';
        case '4': return 'warning';
        default: return '';
      }
    },
    // 来源单据类型格式化
    formatSourceDocType(sourceDocType) {
      const option = this.sourceDocTypeOptions.find(item => item.value === sourceDocType);
      return option ? option.label : sourceDocType;
    },
    // 检测结果格式化
    formatCheckResult(checkResult) {
      const option = this.checkResultOptions.find(item => item.value === checkResult);
      return option ? option.label : checkResult;
    },
    // 检测结果标签类型
    checkResultTag(checkResult) {
      switch (checkResult) {
        case '1': return 'success';
        case '2': return 'danger';
        case '3': return 'info';
        default: return '';
      }
    },
    // 单据状态格式化
    formatStatus(status) {
      const option = this.statusOptions.find(item => item.value === status);
      return option ? option.label : status;
    },
    // 单据状态标签类型
    statusTag(status) {
      switch (status) {
        case '1': return 'info';
        case '2': return 'warning';
        case '3': return 'success';
        default: return '';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 对话框关闭后的处理
    handleDialogClosed() {
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      // 如果RqcForm组件引用存在，调用其重置方法
      if (this.$refs.rqcForm) {
        this.$refs.rqcForm.resetForm();
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 清除高亮ID，因为用户主动搜索了
      this.highlightId = null;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清除高亮ID
      this.highlightId = null;
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rqcId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加退料检验单";
      this.operationType = "add";
    },

    /** 查看按钮操作 */
    handleView(row) {
      if (!row || !row.rqcId) {
        this.$modal.msgWarning("无效的退料检验单ID");
        return;
      }
      this.$router.push({
        path: `/qc/ReturnInspection/detail/${row.rqcId}`
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const rqcId = row.rqcId || this.ids;

      // 清除高亮状态，因为要进入修改模式
      this.highlightId = null;

      this.loading = true; // 添加加载状态

      getRqc(rqcId).then(response => {
        if (response && response.data) {
          console.log('获取到的编辑数据:', response.data);
          this.form = response.data;

          // 确保在数据赋值后再打开对话框
          this.$nextTick(() => {
            this.open = true;
            this.title = "修改退料检验单";
            this.operationType = "edit";
          });
        } else {
          this.$modal.msgError("获取数据失败");
        }
        this.loading = false; // 无论成功失败都关闭加载状态
      }).catch(error => {
        console.error('获取数据异常:', error);
        this.$modal.msgError("获取数据异常: " + (error.message || '未知错误'));
        this.loading = false; // 出错时也关闭加载状态
      });
    },

    /** 提交按钮 */
    submitForm(formData, callback) {
      // 处理日期格式问题
      if (formData.inspectDate && typeof formData.inspectDate === 'string') {
        // 强制将日期格式改为yyyy-MM-dd
        if (formData.inspectDate.includes(' ')) {
          formData.inspectDate = formData.inspectDate.split(' ')[0];
          console.log('已格式化inspectDate:', formData.inspectDate);
        }
      }

      console.log('最终提交的表单数据:', formData);

      if (this.operationType === "add") {
        addRqc(formData).then(response => {
          // 新增成功后显示加载成功消息
          this.$modal.msgSuccess("新增成功");
          
          // 执行回调以关闭加载状态
          if (typeof callback === 'function') {
            callback();
          }

          // 显示正在处理的加载提示
          const loadingInstance = this.$loading({
            lock: true,
            text: '正在处理数据，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          /*
          // 如果新增成功并有退料单ID，从列表中获取最新创建的检测单信息
          if (response.code === 200 && formData.sourceDocId) {
            console.log('表单提交成功，准备获取最新检测单列表...');

            // 定义查询参数，使用表单中的编码或名称精确查询
            const queryParams = {
              rqcCode: formData.rqcCode,
              rqcName: formData.rqcName,
              pageNum: 1,
              pageSize: 10
            };

            // 调用列表API获取最新数据
            listRqc(queryParams).then(listResponse => {
              console.log('获取检测单列表返回:', listResponse);

              if (listResponse && listResponse.rows && listResponse.rows.length > 0) {
                // 找到匹配当前创建的检测单（通常是第一条）
                const newRqc = listResponse.rows[0];
                console.log('找到最新创建的检测单:', newRqc);

                if (newRqc && newRqc.rqcId) {
                  // 使用列表中的完整信息
                  const ipqcId = newRqc.rqcId;
                  const ipqcCode = newRqc.rqcCode;
                  const ipqcName = newRqc.rqcName;

                  console.log('从列表获取到的检测单信息:', {
                    ipqcId, ipqcCode, ipqcName
                  });

                  // 调用子组件的更新方法
                  this.$refs.rqcForm.updateReturnIssueStatus(formData.sourceDocId, ipqcId, ipqcCode, ipqcName);
                } else {
                  console.error('获取到的检测单信息不完整');
                }
              } else {
                console.error('未找到新创建的检测单记录');
              }
            }).catch(err => {
              console.error('获取检测单列表失败:', err);
            });
          }
          */

          // 设置一个短暂的延迟关闭对话框，以展示加载完成效果
          setTimeout(() => {
            // 关闭加载提示
            if (loadingInstance) {
              loadingInstance.close();
            }
            this.open = false;
            this.getList();
          }, 500);
        }).catch(error => {
          // 发生错误时关闭加载
          if (loadingInstance) {
            loadingInstance.close();
          }
          // 执行回调以关闭加载状态
          if (typeof callback === 'function') {
            callback();
          }
          console.error('新增失败:', error);
          this.$modal.msgError('新增失败: ' + (error.message || '未知错误'));
        });
      } else if (this.operationType === "edit") {
        updateRqc(formData).then(response => {
          // 修改成功后不显示提示，静默处理
          // 设置一个短暂的延迟关闭对话框，以展示加载完成效果
          setTimeout(() => {
            this.open = false;
            this.getList();
          }, 500);
          
          // 执行回调以关闭加载状态
          if (typeof callback === 'function') {
            callback();
          }
        }).catch(error => {
          console.error('修改失败:', error);
          if (error.response && error.response.data) {
            console.error('错误详情:', error.response.data);
          }
          
          // 发生错误时也要执行回调以关闭加载状态
          if (typeof callback === 'function') {
            callback();
          }
          
          this.$modal.msgError('修改失败: ' + (error.message || '未知错误'));
        });
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const rqc = row || {};
      const rqcIds = row.rqcId || this.ids;

      // 检查检测结果是否为待检
      if (rqc.checkResult !== 3 && rqc.checkResult !== '3') {
        this.$modal.msgError("只能删除检测结果为待检的单据");
        return;
      }
      this.$modal.confirm('是否确认删除退料检验单编号为"' + (row.rqcCode || '') + '"的数据项?').then(function() {
        return delRqc(rqcIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 打开缺陷记录对话框 */
    handleDefectRecord(row) {
      if (!row || !row.rqcId) {
        this.$modal.msgWarning("无效的退料检验单ID");
        return;
      }
      this.currentDefectRqcId = row.rqcId;
      this.defectDialogVisible = true;
    },

    // 获取行样式
    getRowStyle(row) {
      const baseStyle = {height: '40px'};
      // 确保row和row.row存在且有效
      if (this.highlightId && row && row.row && row.row.rqcId == this.highlightId) {
        return {
          ...baseStyle,
          backgroundColor: '#fdf5e6', // 淡黄色背景
          fontWeight: 'bold',
          color: '#ff7800'
        };
      }
      return baseStyle;
    }
  }
};
</script>

<style scoped>
.rqc-dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.el-link.el-link--primary {
  font-weight: bold;
  font-size: 14px;
}

.el-link.el-link--primary:hover {
  color: #409EFF;
  text-decoration: underline !important;
}

/* 优化固定列样式 */
::v-deep .el-table__fixed-right {
  height: 100% !important;
}

::v-deep .el-table__fixed-left {
  height: 100% !important;
}

::v-deep .el-table__row td {
  height: 40px !important;
}

/* 确保所有单元格内容垂直居中 */
::v-deep .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 调整按钮单元格内容样式 */
::v-deep .el-table .cell .el-button {
  padding: 3px 0;
  margin: 0 3px;
}

/* 高亮待检行样式 */
.highlight-row {
  background-color: #fdf5e6 !important;
  font-weight: bold;
  color: #ff7800;
}
</style>
